package com.cjh.weixin.controller;

import com.cjh.common.service.UploadService;
import com.cjh.common.wxDto.UpdateWxUserDto;
import com.cjh.common.wxDto.WXAuth;
import com.cjh.common.response.Result;
import com.cjh.common.service.WxUserService;
import com.cjh.weixin.common.handler.NoAuth;
import com.cjh.weixin.common.handler.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cjh
 * @since 2022-01-20
 */
@RestController
@RequestMapping("/wx-user")
@Slf4j
public class WxUserController {
    @Autowired
    WxUserService wxUserService;
    @Value("${wx.secret}")
    private String secret;
    @Value("${wx.appid}")
    private String appid;
    @Autowired
    UploadService uploadService;

    @NoAuth
    @GetMapping("/getSessionId")
    public Result getSessionId(@RequestParam String code) {
        String sessionId = wxUserService.getSessionId(code,secret,appid);
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("sessionId", sessionId);
        return new Result().setCode(0).setMessage("操作成功！").setData(hashMap);
    }
    @NoAuth
    @PostMapping("/authLogin")
    public Result authLogin(@RequestBody WXAuth wxAuth) {
        Result result = wxUserService.authLogin(wxAuth);
        log.info("{}",result);
        return result;
    }

    @GetMapping("/userinfo")
    public Result userinfo(@RequestParam Boolean refresh){
        return wxUserService.userinfo(refresh, UserThreadLocal.get());
    }

    @PostMapping("/uploadAvatar")
    public Result uploadAvatar(@RequestBody MultipartFile file){
        String s = uploadService.uploadFile(file, "wxUserAvatar/");
        return new Result().setCode(0).setMessage("上传成功！").setData(s);
    }

    @PostMapping("/updateWxUser")
    public Result updateUser(@RequestBody UpdateWxUserDto updateWxUserDto) {
        Integer id = UserThreadLocal.get().getId();
        updateWxUserDto.setId(id);
        return wxUserService.updateUser(updateWxUserDto);
    }
}
